<template>
  <div class="app-container jrmx222" v-loading="loading" element-loading-text="拼命加载中">
    <div v-if="!DTUList.length" class="duankai_div">
      <img src="../../assets/img/duankai.png" alt="">
      <div>未连接DTU设备</div>
    </div>
    <el-tabs v-model="uuid" @tab-click="handleClick">
      <el-tab-pane v-for="item in DTUList" :key="item.uuid" :label="item.name" :name="item.uuid">
        <div class="content_div">
          <div class="sx_top">
            <span class="top_span2" style="margin-right: 14px">传感器索引号</span>
            <el-select v-if="lock" size="mini" v-model="two" clearable filterable multiple
              style="width: 240px; margin-top: 27px">
              <el-option v-for="item in list" :label="item.rtuIndex" :value="item.rtuIndex"
                :key="item.rtuIndex"></el-option>
            </el-select>
            <el-input placeholder="已全部选中传感器" v-else size="mini"
              style="width: 240px;margin-top: 27px;color: red;display: inline-block;" disabled></el-input>
            <span v-if="lock"
              style="color: #409EFF;font-size: 14px;cursor: pointer;margin-left: 10px;margin-right: 20px;"
              @click="selectAllRtu">全选</span>
            <span v-else style="color: #409EFF;font-size: 14px;cursor: pointer;margin-left: 10px;margin-right: 20px;"
              @click="selectAllRtu">取消全选</span>
            <!-- <el-input
              size="mini"
              style="margin-right: 14px; width: 240px; margin-top: 27px"
              placeholder="传感器名称"
              v-model="two"
              clearable
            />-->
            <!-- <span class="top_span2" style="margin-right: 14px;margin-left: 14px;">状态</span>
            <el-select
              size="mini"
              v-model="one"
              clearable
              style="margin-right: 14px; width: 240px; margin-top: 27px"
            >
              <el-option label="报警" value="1"></el-option>
              <el-option label="正常" value="2"></el-option>
            </el-select>-->
            <span class="top_span2" style="margin-right: 14px;margin-left: 14px;">日期</span>
            <el-date-picker @change="handleDatePickerChange" size="mini" style="width: 294px;" v-model="dataTime"
              :picker-options="options" unlink-panels format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm"
              type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            <!-- <span class="top_span2" style="margin-right: 14px;margin-left: 14px;">设备状态</span>
            <el-select size="mini" v-model="three1" clearable
              style="margin-right: 14px; width: 240px; margin-top: 27px">
              <el-option label="在线" value="1"></el-option>
              <el-option label="断开" value="2"></el-option>
            </el-select> -->
            <el-button size="mini" style="margin-right: 10px; margin-left: 22px" type="primary"
              @click="getHistoryData">查询</el-button>
            <el-button size="mini" @click="handleReset">重 置</el-button>
          </div>
          <div style="
              box-sizing: border-box;
              padding: 20px;
              background: #fff;
              margin-top: 20px;
            ">
            <div style="margin-bottom: 12px">
              <el-button type="primary" style="margin-right: 10px;" @click="historyFile" icon="el-icon-download"
                size="mini">历史数据拷贝</el-button>
              <!-- <el-button type="primary" style="margin-right: 10px;" icon="el-icon-download" size="mini"
                @click="clickWhole">拷贝全部页</el-button> -->
              <!-- <el-button icon="el-icon-copy-document" style="margin-right: 10px;" size="mini" @click="downloadBackup"
                type="danger">历史数据备份</el-button> -->
              <!-- 确认是否备份 -->
              <!-- <el-button icon="el-icon-copy-document" style="margin-right: 10px;" size="mini" @click="downBack"
                v-if="isBtnShow" type="danger">历史数据备份</el-button> -->
              <!-- 密码 -->
              <el-button icon="el-icon-copy-document" style="margin-right: 10px;" size="mini"
                @click="historyClick('download')" v-if="isBtnShow" type="danger">历史数据备份</el-button>
              <!-- <el-button icon="el-icon-share" size="mini" @click="getBackupFilename" type="danger">恢复历史数据</el-button> -->
              <!-- 确认 -->
              <!-- <el-button icon="el-icon-share" size="mini" @click="setBackupClick" type="danger"
                v-if="isBtnShow">恢复历史数据</el-button> -->
              <!-- 密码 -->
              <el-button icon="el-icon-share" size="mini" @click="historyClick('copy')" type="danger"
                v-if="isBtnShow">恢复历史数据</el-button>
            </div>
            <div class="table_div">
              <el-table ref="multipleTable" height="calc(100vh - 410px)" @selection-change="handleSelectionChange"
                :data="historyList" style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                  background: 'rgba(250, 250, 250, 1)',
                  textAlign: 'center',
                }">
                <!-- <el-table-column type="selection" /> -->
                <el-table-column label="传感器名称" width="300">
                  <template slot-scope="scope">{{`${scope.row.rtuIndex}：${scope.row.rtuName}`}}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                  <template slot-scope="scope">
                    <span style="color: #F56C6C;" v-if="scope.row.dataStatusText == '报警'">报警</span>
                    <span style="color: #fbcf4e;" v-else-if="scope.row.dataStatusText == '预警'">预警</span>
                    <span v-else style="color: #67C23A;">正常</span>
                  </template>
                </el-table-column>
                <el-table-column prop="currentX" label="实时数据-X" width="120">
                  <template slot-scope="scope">
                    <span
                      :class="[scope.row.dataStatusText == '正常' ? 'color_success' : scope.row.dataStatusText == '预警' ? 'color_warning' : 'color_error']">{{Math.round(scope.row.currentX+scope.row.initialX)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="currentY" label="实时数据-Y" width="120">
                  <template slot-scope="scope">
                    <span
                      :class="[scope.row.dataStatusText == '正常' ? 'color_success' : scope.row.dataStatusText == '预警' ? 'color_warning' : 'color_error']">{{Math.round(scope.row.currentY+scope.row.initialY)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="currentZ" label="实时数据-Z" width="120">
                  <template slot-scope="scope">
                    <span
                      :class="[scope.row.dataStatusText == '正常' ? 'color_success' : scope.row.dataStatusText == '预警' ? 'color_warning' : 'color_error']">{{Math.round(scope.row.currentZ+scope.row.initialZ)}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="膨胀方向" width="200">
                  <template slot-scope="scope">
                    <span>
                      X：{{scope.row.measuringThreshold.xDirection == 1 ? '正' : '反'}}
                      Y：{{scope.row.measuringThreshold.yDirection == 1 ? '正' : '反'}}
                      Z：{{scope.row.measuringThreshold.zDirection == 1 ? '正' : '反'}}
                    </span>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="measuringThreshold.warningPositive" label="正向阈值" width="80" />
                <el-table-column prop="measuringThreshold.warningNegative" label="反向阈值" width="80" />
                <el-table-column prop="measuringThreshold.totalRange" label="总量程" width="80" />
                <el-table-column prop="measuringThreshold.thresholdPositive" label="正向量程" width="80" />
                <el-table-column prop="measuringThreshold.thresholdNegative" label="反向量程" width="80" /> -->
                <el-table-column label="正向阈值" width="200">
                  <template slot-scope="scope">
                    <span>
                      X：{{scope.row.measuringThreshold.xDirection == 1?
                      scope.row.measuringThreshold.xWarningPositive:scope.row.measuringThreshold.xThresholdPositive}}
                      Y：{{scope.row.measuringThreshold.yDirection == 1?
                      scope.row.measuringThreshold.yWarningPositive:scope.row.measuringThreshold.yThresholdPositive}}
                      Z：{{scope.row.measuringThreshold.zDirection == 1?
                      scope.row.measuringThreshold.zWarningPositive:scope.row.measuringThreshold.zThresholdPositive}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="反向阈值" width="200">
                  <template slot-scope="scope">
                    <span>
                      X：{{scope.row.measuringThreshold.xDirection == 1 ? scope.row.measuringThreshold.xThresholdNegative
                      : scope.row.measuringThreshold.xWarningNegative}}
                      Y：{{scope.row.measuringThreshold.yDirection == 1 ? scope.row.measuringThreshold.yThresholdNegative
                      : scope.row.measuringThreshold.yWarningNegative}}
                      Z：{{scope.row.measuringThreshold.zDirection == 1 ? scope.row.measuringThreshold.zThresholdNegative
                      : scope.row.measuringThreshold.zWarningNegative}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="总量程" width="200">
                  <template slot-scope="scope">
                    <span>
                      X：{{scope.row.measuringThreshold.xDirection == 1 ?(scope.row.measuringThreshold.xThresholdPositive
                      +
                      Math.abs(scope.row.measuringThreshold.xRangeNegative)):(scope.row.measuringThreshold.xRangePositive
                      + Math.abs(scope.row.measuringThreshold.xThresholdNegative))}}
                      Y：{{scope.row.measuringThreshold.yDirection == 1 ?(scope.row.measuringThreshold.yThresholdPositive
                      +
                      Math.abs(scope.row.measuringThreshold.yRangeNegative)):(scope.row.measuringThreshold.yRangePositive
                      + Math.abs(scope.row.measuringThreshold.yThresholdNegative))}}
                      Z：{{scope.row.measuringThreshold.zDirection == 1 ?(scope.row.measuringThreshold.zThresholdPositive
                      +
                      Math.abs(scope.row.measuringThreshold.zRangeNegative)):(scope.row.measuringThreshold.zRangePositive
                      + Math.abs(scope.row.measuringThreshold.zThresholdNegative))}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="正向量程" width="200">
                  <template slot-scope="scope">
                    <span>
                      X：{{scope.row.measuringThreshold.xDirection == 1
                      ?scope.row.measuringThreshold.xThresholdPositive:scope.row.measuringThreshold.xRangePositive}}
                      Y：{{scope.row.measuringThreshold.yDirection == 1
                      ?scope.row.measuringThreshold.yThresholdPositive:scope.row.measuringThreshold.yRangePositive}}
                      Z：{{scope.row.measuringThreshold.zDirection == 1
                      ?scope.row.measuringThreshold.zThresholdPositive:scope.row.measuringThreshold.zRangePositive}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="反向量程" width="200">
                  <template slot-scope="scope">
                    <span>
                      X：{{scope.row.measuringThreshold.xDirection ==
                      1?scope.row.measuringThreshold.xRangeNegative:scope.row.measuringThreshold.xThresholdNegative}}
                      Y：{{scope.row.measuringThreshold.yDirection ==
                      1?scope.row.measuringThreshold.yRangeNegative:scope.row.measuringThreshold.yThresholdNegative}}
                      Z：{{scope.row.measuringThreshold.zDirection ==
                      1?scope.row.measuringThreshold.zRangeNegative:scope.row.measuringThreshold.zThresholdNegative}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="realTime" label="设备状态" width="80">
                  <template>
                    <span style="color: #67c23a;">●在线</span>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="measuringThreshold.warningPositive" label="正向阈值" width="80" />
                <el-table-column prop="measuringThreshold.warningNegative" label="反向阈值" width="80" />
                <el-table-column prop="measuringThreshold.totalRange" label="总量程" width="80" />
                <el-table-column prop="measuringThreshold.thresholdPositive" label="正向量程" width="80" />
                <el-table-column prop="measuringThreshold.thresholdNegative" label="反向量程" width="80" /> -->
                <el-table-column prop="rssi" label="信号强度" width="80" />
                <el-table-column prop="updateTime" label="更新时间" width="200px" :formatter="handleFormatter" />
              </el-table>
              <div class="fenye_div">
                <el-pagination background :current-page="currentPage" :page-sizes="[100, 200, 300, 400]"
                  :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count"
                  @size-change="handleSizeChange" @current-change="handleCurrentChange" />
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="提示" :visible.sync="historyCopyIsShow" width="30%" :before-close="handleClose">
      <div style="color: red;" v-if="historyType == 'download'">频繁备份，将导致硬盘容量不足</div>
      <div style="color: red;" v-if="historyType == 'copy'">恢复历史数据，将导致现有数据被覆盖</div>
      <div style="margin: 20px 0;">
        <el-input size="mini" placeholder="请输入密码" v-model="historyPassWord"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="historyCopyIsShow = false">取 消</el-button>
        <el-button type="primary" @click="historyCopyEnterClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import * as XLSX from "xlsx";
  import { getManagerDTUInfo, getManagerDTUOnlineStatus } from "@/api/manager";
  import { realTimeData, dataChartData } from "@/api/data";
  import { historyFile, getHistoryData } from "@/api/copy";
  import { downloadBackup, getBackupFilename, uploadBackupRestore, getBackupRunning, getBackupStatus } from "@/api/backups";

  export default {
    data() {
      return {
        // =========
        historyType: "",
        historyPassWord: "",
        historyCopyIsShow: false,
        isBtnShow: false,
        fileInfo: {},
        lock: true,
        dataRtuList: [],
        count: 0,
        historyList: [],
        list: [],
        currentPage: 1,
        pageSize: 100,
        startTimeInSecond: 0,
        endTimeInSecond: 0,
        rtuIndexList: [],
        RTUList: [],
        uuid: "",
        dataList: [],
        loading: false,
        DTUOnlineList: [],
        DTUList: [],
        // =========
        three1: "",
        three2: "",
        options: {
          // 时间不能大于当前时间   最小日期不能小于5年
          disabledDate: time => {
            return (
              time.getTime() > Date.now() ||
              time.getTime() < new Date("2019/07/25 00:00:00").getTime() - 8.64e7
            );
          },
          selectableRange: "00:00:00 - 23:59:59"
        },
        dataTime: [],
        sheets: [],
        multiSelectedGroups: [],
        one: "",
        currentPage: 1,
        index: 0,
        two: [],
        filterTableData: [],
        isShow: false,
      };
    },
    created() {
      // this.handleClick();
      // 获取DTU
      this.getManagerDTUOnlineStatus();
      if (localStorage.getItem("userType") == "admin" || localStorage.getItem("userType") == "admin_plus") {
        this.isBtnShow = true;
      }
    },
    methods: {
      historyClick(type) {
        this.historyType = type;
        this.historyPassWord = "";
        this.historyCopyIsShow = true;
      },
      async historyCopyEnterClick() {
        if (this.historyType == "download") { // 下载
          if (this.historyPassWord == "**123456") {
            this.historyCopyIsShow = false;
            await this.downloadBackup();
          } else {
            this.$message.error("密码输入错误");
          }
        } else if (this.historyType == "copy") { // 恢复
          if (this.historyPassWord == "**654321") {
            this.historyCopyIsShow = false;
            await this.getBackupFilename();
          } else {
            this.$message.error("密码输入错误");
          }
        }
      },
      // 恢复历史数据按钮点击事件
      setBackupClick() {
        this.$confirm("历史数据恢复需要一段时间，是否继续此操作？", "确认恢复", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.getBackupFilename();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      },
      // 历史数据备份按钮点击事件
      downBack() {
        this.$confirm("历史数据备份需要一段时间，是否继续此操作？", "确认备份", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.downloadBackup();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      },
      // 备份完成状态
      async getBackupStatus() {
        try {
          const { code, result, message } = await getBackupStatus();
          if (code == 0) {
            if (result) {
              this.$message.success("历史数据备份成功");
            } else {
              this.$message.error(message);
            }
            this.loading = false;
          }
        } catch (error) {
          console.log("备份是否运行接口报错", error);
          this.loading = false;
        }
      },
      // 上传备份数据
      async uploadBackupRestore() {
        try {
          const info = {
            postgresBinDirectory: "D:\\deformation-monitor\\PostgreSQL\\14\\bin",
            // postgresBinDirectory: workDirectory,
            workDirectory: "D:\\deformation-monitor\\PostgreSQL\\14\\bin",
            clearAllDataBeforeRestore: true,
          };
          const { code, message } = await uploadBackupRestore(info);
          if (code == 0) {
            setTimeout(() => {
              this.$message.success("恢复成功");
              this.loading = false;
            }, 30000);
          }
        } catch (error) {
          this.loading = false;
          console.log("上传备份数据接口报错", error);
        }
      },
      // 备份是否运行
      async getBackupRunning() {
        try {
          const { code, result } = await getBackupRunning();
          if (code == 0) {
            await this.getBackupStatus();
          }
        } catch (error) {
          console.log("备份是否运行接口报错", error);
          this.loading = false;
        }
      },
      // 获取备份文件
      async getBackupFilename() {
        try {
          this.loading = true;
          const { code, result: { dataFile, otherDataFile, logFile } } = await getBackupFilename();
          if (code == 0) {
            await this.uploadBackupRestore(otherDataFile);
          }
        } catch (error) {
          this.loading = false;
          console.log(error);
        }
      },
      // 下载备份文件
      async downloadBackup() {
        try {
          this.loading = true;
          const info = {
            postgresBinDirectory: "D:\\deformation-monitor\\PostgreSQL\\14\\bin",
            outputDirectory: "D:\\deformation-monitor\\PostgreSQL\\14\\bin"
          };
          console.log("备份参数", info);
          const { code } = await downloadBackup(info);
          if (code == 0) {
            await this.getBackupRunning();
          }
        } catch (error) {
          this.loading = false;
          console.log("下载备份文件接口报错", error);
        }
      },
      selectAllRtu() {
        this.lock = !this.lock;
        if (!this.lock) {
          this.two = this.list.map(item => item.rtuIndex);
        } else {
          this.two = [];
        }
      },
      // 获取历史数据
      async getHistoryData() {
        try {
          this.loading = true;
          const info = {
            uuid: this.uuid,
            startTimeInSecond: this.startTimeInSecond || Math.floor((Date.now() / 1000) - (7 * 24 * 60 * 60)),
            endTimeInSecond: this.endTimeInSecond || Math.floor(Date.now() / 1000),
            rtuIndex: this.two.length == 0 ? [this.list[0].rtuIndex] : this.two,
            online: true,
            pageNo: this.currentPage,
            pageSize: this.pageSize
          };
          const { code, result: { data, totalCount } } = await getHistoryData(info);
          if (code == 0) {
            this.loading = false;
            this.historyList = JSON.parse(JSON.stringify(data));
            // console.log("信号强度", data.map(item => item.rssi));
            this.count = totalCount;
          }
        } catch (error) {
          this.loading = false;
          console.log("获取历史数据接口报错", error);
        }
      },
      // 下载历史文件
      async historyFile() {
        try {
          if (this.historyList.length == 0) {
            this.$message("暂无数据");
            return;
          }
          const info = {
            uuid: this.uuid,
            startTimeInSecond: this.startTimeInSecond || Math.floor((Date.now() / 1000) - (7 * 24 * 60 * 60)),
            endTimeInSecond: this.endTimeInSecond || Math.floor(Date.now() / 1000),
            rtuIndex: this.two.length == 0 ? [this.list[0].rtuIndex] : this.two,
            online: true,
            // pageNo: this.currentPage,
            // pageSize: this.pageSize,
            pageNo: null,
            pageSize: null
          };
          const { result, code, message } = await historyFile(info);
          if (code == 0) {
            const src = `${process.env.VUE_APP_BASE_API}${result}`;
            window.open(src, "_self");
            // this.downExcel(src, result);
          }
        } catch (error) {
          console.log("下载历史文件接口出错了", error);
        }
      },
      handleDatePickerChange() {
        if (this.dataTime.length > 0) {
          this.startTimeInSecond = new Date(this.dataTime[0]).getTime() / 1000;
          this.endTimeInSecond = new Date(this.dataTime[1]).getTime() / 1000;
        }
      },
      downExcel(url, fileName) {
        const link = document.createElement('a');
        let blob = new Blob([url], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        let objectUrl = window.URL.createObjectURL(blob);
        link.href = objectUrl;
        // link.download = fileName;
        const elementA = document.querySelector('.view-container');
        link.style.display = 'none';
        elementA?.append(link);
        link.click();
        elementA?.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      },
      handleFormatter(row) {
        return `${new Date(row.dataTime).getFullYear()}-${new Date(row.dataTime).getMonth() + 1}-${new Date(row.dataTime).getDate()} ${new Date(row.dataTime).getHours()}:${new Date(row.dataTime).getMinutes() < 10 ? "0" + new Date(row.dataTime).getMinutes() : new Date(row.dataTime).getMinutes()}`;
      },
      statusFun(row) {
        const { currentX, currentY, currentZ, measuringThreshold: { warningPositive, warningNegative, thresholdNegative, thresholdPositive } } = row;
        if (currentX > thresholdPositive || currentY > thresholdPositive || currentZ > thresholdPositive) {
          return "报警";
        } else if ((currentX < warningNegative || currentY < warningNegative || currentZ < warningNegative)) {
          return "报警";
        } else if ((currentX < 0 && currentX > warningNegative) || (currentY < 0 && currentY > warningNegative) || (currentZ < 0 && currentZ > warningNegative)) {
          return "预警";
        } else if ((currentX > warningPositive && currentX < thresholdPositive) || (currentY > warningPositive && currentY < thresholdPositive) || (currentZ > warningPositive && currentZ < thresholdPositive)) {
          return "预警";
        } else {
          return "正常";
        }
      },
      async realTimeData() {
        try {
          this.loading = true;
          const { code, result: { data }, message } = await realTimeData({
            dtuUuid: this.uuid,
            rtuOnline: true
          });
          if (code == 0) {
            this.dataList = JSON.parse(JSON.stringify(data));
            this.dataList.sort((firstItem, secondItem) => firstItem.rtuIndex - secondItem.rtuIndex);
            this.list = JSON.parse(JSON.stringify(this.dataList));
            this.dataRtuList = JSON.parse(JSON.stringify(this.list));
            this.RTUList = JSON.parse(JSON.stringify(this.dataList));
            this.loading = false;
          }
        } catch (err) {
          console.log("调用接口报错了获取RTU", err);
        }
      },
      // 获取DTU在线状态
      async getManagerDTUOnlineStatus() {
        try {
          this.loading = true;
          const { result, message, code } = await getManagerDTUOnlineStatus();
          if (code == 0) {
            this.DTUOnlineList = result.filter(item => item.online);
            this.uuid = this.DTUOnlineList[0].uuid;
            await this.getManagerDTUInfo();
          }
        } catch (err) {
          console.log("调用接口报错了", err);
        }
      },
      // 获取全部DTU信息
      async getManagerDTUInfo() {
        try {
          const { result: { data }, message, code } = await getManagerDTUInfo();
          const list = [];
          if (code == 0) {
            for (let i = 0; i < this.DTUOnlineList.length; i++) {
              const onLineUuid = this.DTUOnlineList[i].uuid;
              for (let j = 0; j < data.length; j++) {
                if (data[j].uuid == onLineUuid) {
                  list.push(data[j]);
                }
              }
            }
            this.DTUList = list;
            this.handleClick();
          }
        } catch (err) {
          this.loading = false;
          console.log("调用接口报错了", err);
        }
      },
      async clickWhole() {
        if (!this.two.length) {
          this.$message("请选择要拷贝的传感器");
          return;
        }
        if (!this.dataTime.length) {
          this.$message("请选择日期");
          return;
        }
        if (this.historyList.length == 0) {
          this.$message("暂无要拷贝数据");
          return;
        }
        try {
          const info = {
            uuid: this.uuid,
            startTimeInSecond: this.startTimeInSecond,
            endTimeInSecond: this.endTimeInSecond,
            rtuIndex: this.two,
            online: true,
            pageNo: this.currentPage,
            pageSize: this.count
          };
          const { result, code, message } = await historyFile(info);
          if (code == 0) {
            // const src = `${process.env.VUE_APP_BASE_API}${result}`;
            const src = `${process.env.VUE_APP_BASE_API}${result}`;
            window.open(src, "_self");
            // this.downExcel(src, result);
          }
        } catch (error) {
          console.log("下载历史文件接口出错了", error);
        }
      },
      clickFile() {
        if (!this.two.length) {
          this.$message("请选择要拷贝的传感器");
          return;
        }
        if (!this.dataTime.length) {
          this.$message("请选择日期");
          return;
        }
        if (this.historyList.length == 0) {
          this.$message("暂无要拷贝数据");
          return;
        }
        this.historyFile();
      },
      // 导出excel
      exportExcel() {
        if (!this.multiSelectedGroups.length) {
          this.$message("请选择要拷贝的传感器");
          return;
        }
        if (!this.dataTime.length) {
          this.$message("请选择日期");
          return;
        }
        // this.sheets = this.sheetData(this.filterTableData);
        this.sheets = this.sheetData(this.multiSelectedGroups);

        const wb = XLSX.utils.book_new(); // 创建一个新的workbook

        // 循环添加每个sheet
        this.sheets.forEach(sheet => {
          const ws = XLSX.utils.aoa_to_sheet(sheet.data); // 将json转换为sheet
          XLSX.utils.book_append_sheet(wb, ws, sheet.name); // 向workbook中添加sheet
        });

        // 导出excel
        const wopts = { bookType: "xlsx", bookSST: false, type: "array" };
        const wbout = XLSX.write(wb, wopts);
        const blob = new Blob([wbout], { type: "application/octet-stream" });
        const href = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = href;
        link.download = "数据总集.xlsx";
        link.click();
        setTimeout(function () {
          URL.revokeObjectURL(href);
        }, 100);
      },
      sheetData(data) {
        const classifiedData = data.reduce((acc, obj) => {
          const name = obj.name;
          const existingItem = acc.find(item => item.name === name);

          if (existingItem) {
            existingItem.data.push([
              obj.parentName,
              obj.name,
              '正常',
              'X(-85) Y(-85) Z(-85)',
              '已连接',
              "正常",
              600,
              -50,
              800,
              700,
              -100,
              obj.updateTime
            ]);
          } else {
            acc.push({
              name,
              data: [
                [
                  "锅炉名称",
                  "传感器名称",
                  "状态",
                  "实时数据",
                  "连接状态",
                  "设备状态",
                  "正向阈值",
                  "反向阈值",
                  "总量程",
                  "正向量程",
                  "反向量程",
                  "更新时间"
                ],
                [
                  obj.parentName,
                  obj.name,
                  '正常',
                  'X(-85) Y(-85) Z(-85)',
                  '已连接',
                  "正常",
                  600,
                  -50,
                  800,
                  700,
                  -100,
                  obj.updateTime
                ]
              ]
            });
          }

          return acc;
        }, []);
        return classifiedData;
      },
      // 回调表格选择的数据 当选择项发生变化时会触发该事件
      handleSelectionChange(list) {
        this.multiSelectedGroups = [...list];
        this.rtuIndexList = this.multiSelectedGroups.map(item => item.rtuIndex);
      },
      // 限制数量方法
      limitFn(list) {
        if (this.activeName == "first") {
          this.$refs.multipleTable.clearSelection(); //用于多选表格，清空用户的选择
          for (let i = 0; i < 3; i++) {
            this.$refs.multipleTable.toggleRowSelection(list[i]); //用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
          }
        } else {
          this.$refs.multipleTable2.clearSelection(); //用于多选表格，清空用户的选择
          for (let i = 0; i < 3; i++) {
            this.$refs.multipleTable2.toggleRowSelection(list[i]); //用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
          }
        }
      },
      async handleClick() {
        this.two = [];
        this.dataTime = [];
        this.startTimeInSecond = 0;
        this.endTimeInSecond = 0;
        await this.realTimeData();
        await this.getHistoryData();
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getHistoryData();
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getHistoryData();
      },
      // handleSearch() {
      //   this.RTUList = this.dataList.filter(item => item.rtuIndex == this.two);
      // },
      async handleReset() {
        this.one = this.three1 = this.three2 = "";
        this.two = [];
        this.dataTime = [];
        this.startTimeInSecond = 0;
        this.endTimeInSecond = 0;
        this.lock = true;
        await this.realTimeData();
        await this.getHistoryData();
        // this.RTUList = JSON.parse(JSON.stringify(this.dataList));
      },
    }
  };
</script>

<style lang="scss">
  .jrmx222 {
    .fenye_div {
      margin-top: 30px;
      text-align: right;
    }

    .table_div {
      height: calc(100vh - 250px);
    }

    .top_span2 {
      /** 文本1 */
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
    }

    .sx_top {
      height: 80px;
      background-color: #fff;
      box-sizing: border-box;
      padding: 0 0 29px 19px;
    }

    .el-tabs__nav-scroll {
      background-color: #fff;
      padding-left: 34px;
    }

    .content_div {
      height: calc(100vh - 150px);
    }

    .el-tabs__nav-wrap::after {
      background-color: transparent !important;
    }
  }

  .el-dialog__body {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
  }

  .btn {
    display: flex;
    justify-content: center;
    margin-top: 140px;
  }

  .ball_div {
    box-sizing: border-box;
    padding: 20px;
    padding-top: 0;
    overflow-y: scroll;
    height: calc(100vh - 77px);
  }

  .red {
    color: #f56c6c;
  }

  .green {
    color: #67c23a;
  }
</style>